import pygame
from plane_sprites import *

# SCREEN_RECT = pygame.Rect(0, 0, 250, 400)
# FRAME_PER_SEC = 60

class PlaneGame(object):

    def __init__(self):

        print("游戏初始化")
        # 创建窗口
        self.screen = pygame.display.set_mode(SCREEN_RECT.size)
        #　创建时钟
        self.clock = pygame.time.Clock()
        # 创建精灵，调用私有方法
        self.__creatsprint()
        # 设定定时器事件，１秒出一架飞机
        pygame.time.set_timer(CREATE_EMEMY_EVENT, 1000)
        pygame.time.set_timer(HERO_FIRE_EVENT, 500)

    def __creatsprint(self):

        bg1 = BackGround()
        bg2 = BackGround(True)
        self.back_group = pygame.sprite.Group(bg1, bg2)
        self.enemy_group = pygame.sprite.Group()
        self.hero = Hero()
        self.hero_group = pygame.sprite.Group(self.hero)


    def startgame(self):

        print("开始游戏")

        while True:

            # 设置时钟
            self.clock.tick(FRAME_PER_SEC)
            # 事件监听
            self.__event_hanlder()
            # 碰撞检测
            self.__check_collide()
            #　更新和绘制精灵
            self.__updata_sprints()
            # 更新显示
            pygame.display.update()



    def __event_hanlder(self):

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                PlaneGame.__game_over()
            elif event.type == CREATE_EMEMY_EVENT:
                # print("每秒敌机出场一架")
                enemy = Eneny()
                self.enemy_group.add(enemy)

            elif event.type == HERO_FIRE_EVENT:

                self.hero.fire()

            # elif event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
            #     print("按下右键...")
            key_press = pygame.key.get_pressed()
            if key_press[pygame.K_RIGHT]:
                # print("向右移动...")
                self.hero.speed = 2

            elif key_press[pygame.K_LEFT]:

                self.hero.speed = -2
            else:
                self.hero.speed = 0

    def __check_collide(self):

        pygame.sprite.groupcollide(self.hero.bullet_gruop, self.enemy_group, True, True)
        enemy_list = pygame.sprite.spritecollide(self.hero, self.enemy_group, True)

        if len(enemy_list) > 0:

            self.hero.kill()

            PlaneGame.__game_over()
        pass

    def __updata_sprints(self):

        self.back_group.update()
        self.back_group.draw(self.screen)
        self.enemy_group.update()
        self.enemy_group.draw(self.screen)
        self.hero_group.update()
        self.hero_group.draw(self.screen)

        self.hero.bullet_gruop.update()
        self.hero.bullet_gruop.draw(self.screen)
    @staticmethod
    def __game_over():

        print("英雄牺牲，游戏结束")

        pygame.quit()

        exit()


if __name__ == '__main__':

    game = PlaneGame()

    game.startgame()


